package cn.zzf.core;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author GaoFeng2017
 * @date 2018-02-13 17:03:12
 **/

public class ClassTableHandler implements ContentHandler {
    @Override
    public void handle(String content,String id) {
        content = content.replaceAll("</tr>","</tr>\n");
        content = content.replaceAll("</td>","</td>\n");
        content = content.replaceAll("</TD>","</TD>\n");

        /*.replaceAll("\\[","!![")*/
        content = content.replaceAll("&nbsp;","!!")
                .replaceAll("]","]!!")
                .replaceAll("\\)",")!!")
                .replaceAll("(\\s{1}\\[)","!![")
                /*.replaceAll("人数","!!人数")*/
                .replaceAll("(人数：\\d+)\\s?","")
                .replaceAll("(\\d节)","$1!!")
                .replaceAll("(!!!!)","!!")
                .replaceAll("(!! )","!!")
                .replaceAll("(!!\\s{1}!!)","!!")
                .replaceAll("( !!)","!!")
                .replaceAll("(,)","??")
                .replaceAll("(\\?\\?\\s{1})","??");

        Map<String,String> map = parseContent(content);
        map.put("tid",id);
        try {
            CrawerUtils.saveToProperties(map,"H:\\2018_table\\" + map.get("name") + map.get("tid"));
        } catch (IOException e) {
            throw  new RuntimeException(e);
        }
    }

    public Map<String, String> parseContent(String content) {
        Pattern titlePattern = Pattern.compile("(部门.+)<");
        Matcher tmr = titlePattern.matcher(content);
        Map<String,String> map = new LinkedHashMap<>(11);

        String title = "";
        /*获取标题*/
        if (tmr.find()) {
            title = tmr.group();
            title = title.substring(0,title.length() - 1);
        }

        System.out.println(title);
        String[] teacherInfo = title.split("!!");
        map.put("depart",teacherInfo[0].substring(3));
        map.put("name",teacherInfo[1].substring(3));
        map.put("sex",teacherInfo[2].substring(3));

        /*获取课程*/
        Pattern tablePattern = Pattern.compile("(<td valign=top width=\\'13\\%\\'>).*(<\\/td>)");
        String[] tables = {"","","","","","",""};

        Matcher cmr = tablePattern.matcher(content);

        int count = 0;
        while (cmr.find()) {
            String result = cmr.group();
            result = result.replace("<td valign=top width='13%'>","")
                    .replace("</td>"," ");
            if (!Objects.equals(result.trim(),"")) {
                tables[count%7] = tables[count%7]  + result.replaceAll("(\\d{4})([^]\\[节\\s]+(!!\\[){1}[^]\\[]+周])","$1,$2") + ",";
            }
            count++;
        }

        String[] week = new String[]{"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};

        for(int i = 0;i < week.length;i++) {
            map.put(week[i],tables[i]);
        }

        System.out.println(map);
        return map;
    }


}
